/* eslint-disable vue/no-unused-vars */
<template>
  <div class="instiutionTable">
    <div class="tableBox" ref="instiutionBox">
      <u-table
        :data="instiutionTableData"
        :border="true"
        :max-height="tableHeight"
        highlight-current-row
        :span-method="arraySpanMethod"
        :header-cell-style="headerCellStyle"
        :show-overflow-tooltip="true"
        ref="instiutionTable"
        v-loading="showLoading"
        @select="selectChange"
        @select-all="selectAll"
        class="m7-table"
      >
        <template v-for="(item, index) in instiutionTableHeader">
          <u-table-column
            v-if="item.type === 'select'"
            :key="index"
            v-bind="item"
            :border-line="false"
            type="selection"
            fixed="left"
            width="55"
          >
          </u-table-column>
          <u-table-column
            :key="index"
            :sortable="item.isSort"
            v-else-if="item.custom"
            v-bind="item"
          >
            <template slot-scope="scope">
              <slot :name="item.prop" :scope="scope" :item="item" />
            </template>
          </u-table-column>
          <u-table-column
            :key="index"
            :sortable="item.isSort"
            v-else-if="item.isStatus"
            v-bind="item"
          >
            <template slot-scope="scope">
              {{ statusMap[scope.row[item.prop]] }}
            </template>
          </u-table-column>
          <u-table-column
            :key="index"
            :sortable="item.isSort"
            v-else-if="item.isDictionary"
            v-bind="item"
          >
            <template slot-scope="scope">
              <span v-show="item.showStatusIcon">
                <i
                  class="V7_iconfont"
                  :class="item.dictionary[scope.row[item.prop]].iconClass"
                  style="font-size: 12px"
                ></i>
              </span>
              {{ item.dictionary[scope.row[item.prop]].name }}
            </template>
          </u-table-column>
          <u-table-column
            v-else-if="item.handlers"
            :border-line="false"
            :key="index"
            :width="item.width"
            v-bind="item"
            fixed="right"
          >
            <template slot-scope="scope">
              <span
                v-for="(handler, index) in item.handlers"
                @click.stop="handler.handleFn(scope)"
                :key="index"
              >
                <span
                  class="opera-span"
                  :class="handler.className"
                  v-if="
                    scope.row[handler.field] === handler.status &&
                    (!handler.isShowSystemDelBtn ||
                      scope.row.createUser !== 'system') &&
                    !scope.row.isDefault
                  "
                  >{{ handler.name }}</span
                >
              </span>
            </template>
          </u-table-column>
          <u-table-column
            v-else-if="item.type === 'inputNumber'"
            :key="index"
            v-bind="item"
          >
            <template slot-scope="{ row }">
              <el-input-number
                v-model="row[item.prop]"
                :controls="false"
                style="width: 60%"
              />
            </template>
          </u-table-column>
          <u-table-column v-else-if="item.jumpFun" :key="index" v-bind="item">
            <template slot-scope="{ row }">
              <span
                @click.stop="item.jumpFun.handleFn(row)"
                class="jump-page"
                >{{ row[item.prop] }}</span
              >
            </template>
          </u-table-column>
          <u-table-column v-else-if="item.customerField" :key="index" v-bind="item">
            <template slot-scope="{ row }">
              <customDisplay :data="row" :fieldProp="item"></customDisplay>
            </template>
          </u-table-column>
          <u-table-column
            :key="index"
            :sortable="item.isSort"
            :show-overflow-tooltip="item.width && item.width > 0"
            v-else
            v-bind="item"
          >
          </u-table-column>
        </template>
        <u-table-column
          align="center"
          fixed="right"
          width="40"
          :resizable="false"
        >
          <template #header>
            <el-dropdown v-if="isCustomerCol" trigger="click" @visible-change="isClick = !isClick">
              <span class="el-dropdown-link">
                <i :class="{'icon-active': isClick, 'V7_iconfont': true, 'V7_iconV7tubiao_zidingyi': true}"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <customHeader
                  :data="customerTableHeader"
                  @check-change="handleHeaderCheckChange"
                ></customHeader>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <div class="batch-box" v-if="isAllCheck ? pages.total : selectLength">
        <div class="batch-oprate">
          <el-checkbox v-model="isAllCheck" @change="checkAllData"
            >全选</el-checkbox
          >
          <span class="selected-count"
            >已选择<span class="selectedNum">{{
              isAllCheck ? pages.total : selectLength
            }}</span
            >项</span
          >
          <span class="selectedBtn">
            <el-button
              type="text"
              v-for="(item, index) in batchOperate"
              :key="index"
              @click="batchClick(item)"
            >
              {{ item.name }}
            </el-button>
          </span>
          <span
            class="V7_iconfont V7_iconV7tubiao_guanbi oprate-close"
            @click="cancelSelectFun"
          ></span>
        </div>
      </div>
    </div>
    <el-pagination
      v-if="isShowPage"
      :class="isAllCheck ? 'all-check-mask' : ''"
      class="pages"
      @current-change="handleCurrentChange"
      @size-change="sizeChange"
      :current-page.sync="pages.current"
      :page-size="pages.pageSize || 10"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pages.total"
    >
    </el-pagination>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch, Ref } from 'vue-property-decorator'
import customHeader from '@/common/views/institutionTable/customHeader.vue'
import cloneDeep from 'lodash/cloneDeep'
import customDisplay from './customDisplay.vue'

import { Table as UTable } from 'element-ui'
interface ArrayObj {
  props: string
}
@Component({
  name: 'instiutionTable',
  components: {
    customHeader,
    customDisplay
  }
})
export default class InstiutionTable extends Vue {
  @Prop(Array) public instiutionTableHeader!: ArrayObj[] // 表头
  @Prop(Array) public customerTableHeader!: ArrayObj[] // 自定义表头
  @Prop(Array) public instiutionTableData!: ArrayObj[] // 表格数据
  @Prop(Object) public statusMap!: any
  @Prop(Object) public pages!: any // 翻页数据
  @Prop({ default: () => [] }) private batchOperate!: any[] // 批量操作的数据
  @Prop({ default: true }) private isShowPage!: true
  @Prop({ default: false }) private isCustomerCol!: boolean
  @Ref() private readonly instiutionTable!: UTable
  private pageSelect: any = {}
  private showLoading: any = false
  private tableHeight: number = 0
  private checkList: any = []
  private isAllCheck: boolean = false
  private isClick: boolean = false
  get getHeadersShowLength () {
    let length = 0
    this.checkList.forEach((item) => {
      if (item.show) {
        length++
      }
    })
    return length
  }

  get selectLength () { // 获取每页的选中数
    let length: any = 0
    Object.keys(this.pageSelect).forEach((page) => {
      length += this.pageSelect[page].length
    })
    return length
  }

  get getBatchShow () { // 是否显示批量操作栏
    return this.selectLength > 0 || this.isAllCheck
  }

  private handleHeaderCheckChange (val) {
    this.$emit('headrChange', val)
  }

  private checkAllData (data) { // 选择全部
    this.isAllCheck = data
    if (data) { // 全选
      this.$set(this.pageSelect, (this.pages as any).current, cloneDeep(this.instiutionTableData)) // 存储当页数据
      this.clearSelection() // 先取消选择
      this.instiutionTableData.forEach(item => { // 当前页全选
        this.instiutionTable.toggleRowSelection([{
          row: item,
          select: true
        }]) // 当前页全选
      })
    } else { // 取消全选
      this.cancelSelectFun()
    }
  }

  private handleCurrentChange (page: number) { // 点击翻页
    this.$emit('currentChange', page)
  }

  private selectChange (selection, row) { // 单独选择某一个
    this.isAllCheck = false
    if (selection && selection.length === this.pages.total) {
      this.isAllCheck = true
    }
    this.$set(this.pageSelect, (this.pages as any).current, cloneDeep(selection))
    this.tableHeightFun()
  }

  private selectAll (selection) { // 单页全选
    if (selection && selection.length === this.pages.total) {
      this.isAllCheck = true
    }
    if (selection) {
      this.$set(this.pageSelect, (this.pages as any).current, cloneDeep(selection))
      if (selection.length <= 0) {
        this.isAllCheck = false
      }
    } else {
      this.$set(this.pageSelect, (this.pages as any).current, [])
      this.isAllCheck = false
    }
  }

  public cancelSelectFun () { // 取消选择
    this.$set(this, 'pageSelect', {}) // 清空当前选择项
    this.isAllCheck = false
    this.clearSelection() // 取消checked
  }

  private arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
    const oprateIndex = this.getHeadersShowLength - 1
    if (columnIndex === oprateIndex) {
      return [1, 3]
    }
  }

  private sizeChange (size: number) { // 每页几条
    this.$emit('sizeChange', size)
  }

  private batchClick (item: any) { // 点击批量操作
    const selectList: any = []
    Object.keys(this.pageSelect).forEach((page) => { // 整理跨页操作的ids
      if (this.pageSelect[page].length > 0) {
        this.pageSelect[page].forEach((pageItem) => {
          if (item.type !== 'business') {
            selectList.push(pageItem._id)
          } else {
            selectList.push(pageItem.id)
          }
        })
      }
    })
    this.$emit('batchClick', item.action, this.isAllCheck || selectList)
  }

  private clearSelection () {
    this.instiutionTable.clearSelection()
  }

  // private handleCheckChange (dataList) {
  //   this.showLoading = true
  //   setTimeout(() => {
  //     this.showLoading = false
  //   }, 400)
  //   this.$set(this, 'checkList', dataList)
  //   this.$emit('checkHeadersChange', dataList)
  // }

  private headerCellStyle ({ row, column, rowIndex, columnIndex }) {
    const oprateIndex = this.getHeadersShowLength - 1
    if (columnIndex === oprateIndex) {
      return { borderRight: '1px solid transparent' }
    }
  }

  private tableHeightFun () {
    if (this.$refs.instiutionBox) {
      const con: any = this.$refs.instiutionBox
      const $el = con || {}
      const conStyles = window.getComputedStyle($el)
      const height = parseInt(conStyles.height, 10)
      if (this.selectLength > 0) {
        this.tableHeight = height - 12 - 50
      } else {
        this.tableHeight = height - 12
      }
    }
  }

  @Watch('getBatchShow')
  private getBatchShowChange () {
    this.tableHeightFun() // 批量操作条消失，高度要重新计算
  }

  @Watch('instiutionTableData')
  private instiutionTableDataChange (list) {
    this.$nextTick(() => {
      this.instiutionTable.clearSelection()
      const rows = cloneDeep(this.pageSelect[(this.pages as any).current])
      if (rows && rows.length > 0) {
        rows.forEach(row => {
          list.forEach((lItem, index) => {
            if (lItem._id === row._id) {
              this.instiutionTable.toggleRowSelection([{
                row: list[index],
                select: true
              }])
            }
          })
        })
      }
    })
  }

  private mounted () {
    this.tableHeightFun()
    // 动态设置表格高度
    window.addEventListener('resize', () => this.tableHeightFun(), false)
  }

  private beforeDestroy () {
    window.removeEventListener('resize', () => this.tableHeightFun())
  }
}
</script>
<style lang="stylus" scoped>
.instiutionTable
  display flex
  flex-direction column
  justify-content space-between
  height 100%
  font-size 12px
  width 100%
  /deep/ .el-table__column-resize-proxy
          border-left: 2px dashed $c-main !important
  /deep/ .el-table--border
          border: none
  /deep/ .el-table--border td
          border-right: 3px solid transparent
  /deep/ .el-table-column--selection
          padding-left: 4px
  /deep/ .el-table--border td:last-child
          border-right: 1px solid #EBEEF5
  /deep/ .el-table--border th
            border-right: 3px solid transparent
  /deep/ .el-table--border th:last-child
          border-right: none !important
  /deep/ .el-table--border th:not(.el-table-column--selection):not(.is-right)::after
            content: ''
            position: absolute
            right 0
            top 25%
            height 50%
            opacity: 0
            width 3px
            background $c-main
            border-radius: 2px
  /deep/ .el-table--border th:not(.el-table-column--selection):not(.is-right):hover::after
          opacity: 1
  .tableBox
    height calc(100% - 60px)
    box-sizing border-box
    padding-top 16px
    display flex
    flex-direction column
    justify-content space-between
    .icon-active
      color $c-main
  .V7_iconV7tubiao_zidingyi
    color $icon-gray
    cursor pointer
  .batch-box
    height 50px
    display flex
    flex-direction column
    justify-content flex-end
    .batch-oprate
      height 40px
      line-height 40px
      background #E5F3FD
      border-radius 4px
      display flex
      align-items center
      padding 0 16px 0
      box-sizing border-box
      position relative
      .selected-count
        padding-left 20px
      .oprate-close
        color $icon-gray
        font-size 14px
        cursor pointer
        position absolute
        right 16px
        &:hover
          color $c-main
  .selectedNum
    display inline-block
    padding 0px 5px
    color $c-main
  .selectedBtn
    margin-left 20px
  .jump-page
    color $c-main
    cursor pointer
.V7_iconV7tubiao_zidingyi
  text-align right
.opera-span
  color $c-main
  margin-right 10px
  cursor pointer
.danger, .red-color
  color $c-danger
.green-color
  color $c-green
.pages
  box-sizing border-box
  display flex
  justify-content flex-end
  height 60px
  align-items center
  position relative
.all-check-mask:after
  content ''
  position absolute
  bottom 0
  left 0
  width 100%
  height 100%
  background hsla(0,0%,100%,0.3)
  z-index 100
  cursor not-allowed
</style>
